<?php
class UserIdentity extends CUserIdentity
{
    private $_id, $_user;

    public function authenticate()
    {
		$userId = Users::getInstance()->authenticate($this->username, $this->password, Users::AUTH_WITH_EMAIL);
		if($userId === Users::AUTH_ERROR_USERNAME_INVALID){
            $this->errorCode=self::ERROR_USERNAME_INVALID;
		}
		else if($userId === Users::AUTH_ERROR_ACCOUNT_LOCKED){
			$this->errorCode=MSG_ERROR_ACCOUNT_LOCKED;
		}
        else if($userId === Users::AUTH_ERROR_PASSWORD_INVALID){
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
		}
        else
        {
			$user = Users::getInstance()->get($userId);
			//load role
			$roles = Roles::getInstance()->getUserRoles($user['user_id'], array(), RETURN_KEY_VALUE_ARRAY);
			
			//load permissions
			$permissions = Permissions::getInstance()->getUserPermissions($user['user_id'], 'helpdesk');
			$allowedPermissions = array();
			foreach($permissions as $R){
				if($R['value'] == 1) array_push($allowedPermissions, $R['permission_name']);
			}
			
            $this->_id=$user['user_id'];
            $this->setState('username', $user['user_username']);
			$this->setState('fullname', $user['user_fullname']);
			$this->setState('roles', $roles);
			$this->setState('permissions', $allowedPermissions);
			$this->_user=$user;
            $this->errorCode=self::ERROR_NONE;
        }
        return !$this->errorCode;
    }
 
    public function getId()
    {
        return $this->_id;
    }
	
	 public function getUser()
    {
        return $this->_user;
    }
}